package com.ai_chat.common.util;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.application.name}")
    private String personal;


    public boolean sendMail(String to,String subject,String text){
        MimeMessage mmm = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mmm);
        try {
            helper.setSubject(subject);
            helper.setText(text);
            helper.setFrom(new InternetAddress(from,personal,"UTF-8"));
            helper.setTo(to);

            javaMailSender.send(mmm);
            return true;
        } catch (UnsupportedEncodingException e) {
            return false;
        } catch (MailException e){
            return false;
        } catch (MessagingException e) {
            return false;
        }

    }
}
